package utils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.struts2.ServletActionContext;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;



public class XmlUtils {
	 //利用dom4j解析xml文件内容，并返回map数据形式  
    public static Map<String,String> paserXmlByDOM4J(String path) throws Exception{  
//        path=ServletActionContext.getServletContext().getRealPath(path);  
        DocumentBuilder db = DocumentBuilderFactory.newInstance()
		.newDocumentBuilder();
        Document doc = (Document) db.parse(new File(path)); 
        Map<String,String> xml=paserXml(doc);  
        return xml;  
    }  
      
    //传入xml格式的string，转化为xml类型，然后解析其内容，返回map数据形式  
    public static Map<String,String> strToXmlAndPaserXml(String strXml) throws Exception{  
        SAXReader reader = new SAXReader();  
        Document doc = reader.read(new ByteArrayInputStream(strXml.getBytes("UTF-8")));  
        Map<String,String> xml=paserXml(doc);  
        return xml;  
    }  
      
      
    //遍历解析xml数据  
    public static Map<String,String> paserXml(Document doc) throws Exception{  
        Map<String,String> xml=new HashMap<String,String>();  
        Element root = doc.getRootElement();  
        Iterator it = root.elementIterator();  
        Element element;  
        while (it.hasNext()) {  
            element = (Element) it.next();  
            xml.put(element.getName(),element.getText());  
        }  
        return xml;  
    }  
}